package servlet.manager;

import entity.Announcement;
import net.sf.json.JSONObject;
import service.manager.AnnouncementService;
import service.manager.impl.AnnouncementServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * AnnouncementUpdServlet
 *
 * @author 谭文斌
 * @since 2023/9/1
 */
@WebServlet("/manager/announcementUpdServlet")
public class AnnouncementUpdServlet extends HttpServlet {
    AnnouncementService service=new AnnouncementServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        PrintWriter out=resp.getWriter();
        JSONObject json = new JSONObject();
        String op=req.getParameter("op");

        if (op == null) {
            int id=Integer.valueOf(req.getParameter("id"));
            Announcement a=service.getId(id);
            req.setAttribute("a",a);
            req.getRequestDispatcher("08edit.jsp").forward(req, resp);
        }
        switch (op) {
            case "upd":
                String id=req.getParameter("id");
                String title=req.getParameter("title");
                String detail=req.getParameter("detail");
                if (title==null || title.equals("") || detail==null || detail.equals("")) {
                    json.put("msg","参数不能为空");
                    json.put("code",1);
                    json.put("data",null);
                }else {
                    Announcement announcement = new Announcement(Integer.valueOf(id), title, detail);
                    int upd = service.upd(announcement);
                    if (upd > 0) {
                        json.put("code", 0);
                        json.put("msg","修改成功");
                        json.put("data",null);
                    }else {
                        json.put("code", 1);
                        json.put("msg","修改失败");
                        json.put("data",null);
                    }
                }
                break;
        }
        out.print(json.toString());
    }
}
